package com.treeman.user;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.treeman.user.exception.UserNotFoundException;
import com.treeman.user.service.UserService;

@Component
public class UserValidator implements Validator {

	@Autowired
	private UserService userService;

	@Override
	public boolean supports(Class<?> arg0) {
		return User.class.equals(arg0);
	}

	@Override
	public void validate(Object arg0, Errors errors) {
		User user = (User) arg0;

		validateUsername(user, errors);

		validatePasswords(user, errors);

		validateEmail(user, errors);
	}

	private void validateUsername(User user, Errors errors) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username",
				"validation.required");

		try {
			userService.getUserByUsername(user.getUsername());
			errors.rejectValue("username", "validation.user.exists");
		} catch (UserNotFoundException e) {
		}
	}

	private void validatePasswords(User user, Errors errors) {

		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password",
				"validation.required");

		if (user.getPassword().length() < 4 && user.getPassword().length() > 20) {
			errors.rejectValue("password", "validation.user.password.lenght");
		} else if (user.getPassword().equals(user.getRepeatedPassword()) == false) {
			errors.rejectValue("password", "validation.user.password.notequal");
		}
	}

	private void validateEmail(User user, Errors errors) {

		String expression = "([._A-Za-z0-9-]+)*@([._A-Za-z0-9-]+)*[a-zA-Z]+";
		if (!user.getEmail().matches(expression)) {
			errors.rejectValue("email", "validation.user.email");
		}

		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email",
				"validation.required");

	}

}
